/**
 * Copyright © 2020 易久批信息技术有限公司. All rights reserved.
 */
package com.dysm.loan;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;

/**
 * 等额本金计算
 * @author xiay
 * @since 2020/12/3 9:45 上午
 */
public class StandOfInterestCal implements InterestCalculate {

    /**
     * 等额本息
     * @param totalAmount
     * @param monthNum
     * @param yearRate
     */
    @Override
    public void calculate(BigDecimal totalAmount, BigDecimal monthNum, BigDecimal yearRate) {
        BigDecimal monthRate = yearRate.divide(BigDecimal.valueOf(12), 6, RoundingMode.HALF_UP);
        BigDecimal temp = BigDecimal.valueOf(1).add(monthRate);
        BigDecimal tempData = BigDecimal.valueOf(Math.pow(temp.doubleValue(), monthNum.doubleValue()));
        BigDecimal currentRepayAmount = (totalAmount.multiply(monthRate).multiply(tempData))
                .divide((tempData.subtract(BigDecimal.valueOf(1))), 6, RoundingMode.HALF_UP);
        BigDecimal totalInterest = currentRepayAmount.multiply(monthNum).subtract(totalAmount);
        System.err.println("--------等额本息开始还款--------");
        recursive(totalAmount, currentRepayAmount, 1, monthNum.intValue(), monthRate);
        String titleMsg = String.format("当前贷款总额：【%s】，年利率：【%s】，还款期数：【%s】，利息总额：【%.2f】", totalAmount,
                yearRate, monthNum, totalInterest);
        System.out.println(titleMsg);
        System.err.println("--------等额本息结束还款--------");
    }


    /**
     * 等额本息
     * @param remainAmount
     * @param perAmount
     * @param currentMonth
     * @param totalMonth
     * @param monthRate
     */
    private static void recursive(BigDecimal remainAmount, BigDecimal perAmount,
                                  Integer currentMonth, Integer totalMonth, BigDecimal monthRate) {
        BigDecimal currentInterest = remainAmount.multiply(monthRate);
        if (Objects.equals(currentMonth, totalMonth + 1)) {
            return;
        } else {
            remainAmount = remainAmount.subtract(perAmount).add(remainAmount.multiply(monthRate));
            String repayMsg = String.format("第【%s】期还款：【%.2f】，本金：【%.2f】，利息：【%.2f】，剩余本金：【%.2f】",
                    currentMonth, perAmount, perAmount.subtract(currentInterest), currentInterest, remainAmount);
            System.out.println(repayMsg);
            currentMonth ++;
            recursive(remainAmount, perAmount, currentMonth, totalMonth, monthRate);
        }
    }
}
